package com.lyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.common.CustomException;
import com.lyl.dto.SetmealDto;
import com.lyl.entity.Setmeal;
import com.lyl.entity.SetmealDish;
import com.lyl.mapper.SetmealMapper;
import com.lyl.service.SetmealDishService;
import com.lyl.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李亚龙
 * @version 1.0
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 保存套餐，同时同时更新setmeal和setmealDish两张表
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);

        //保存套餐和菜品关联信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //设置setmealdish中的setmealId属性
        setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 批量或单个删除套餐及其对应的套餐菜品关联表
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        long count = this.count(queryWrapper);
        if(count > 0){
            //如果不能删除，抛出一个业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }
        //如果可以删除，先删除套餐表中的数据
        this.removeByIds(ids);

        //再删除关系表中的数据
        LambdaQueryWrapper<SetmealDish> queryWrapperSD = new LambdaQueryWrapper<>();
        queryWrapperSD.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapperSD);
    }
}
